<script setup>
import { getStrWidth } from '@/utils'

const props = defineProps(['ways'])
const { ways } = toRefs(props)
const model = defineModel()

const currentWay = computed(() => {
  return ways.value?.find(item => item.name === model.value.name)
})

const isSingle = computed(() => ways.value?.length < 2) //  单种搜索方式
const isInput = computed(() => !currentWay.value?.values?.length)

watch(() => model.value.name, () => {
  model.value.value = ''
  model.value.op = currentWay.value.op
})

// 若右侧可选列表变化，绑定的值默认选中第一项
watch(() => currentWay.value?.values, () => {
  const { values = [] } = currentWay.value || {}
  if (values?.length && values[0].label === '全部')
    model.value.value = ''
})

/** 左边宽度 */
const lfw = computed(() => {
  return `${getStrWidth(currentWay.value?.label) + 40}px`
})

const placeholder = computed(() => {
  const action = isInput.value ? '请输入' : '请选择'
  const { placeholder = '', label = '' } = currentWay.value || {}
  return placeholder || `${action}${label}`
})
</script>

<template>
  <div class="flex-center">
    <!-- 左侧文本或选择框 -->
    <div class="left">
      <span v-if="isSingle" class="label flex-center">{{ ways[0]?.label || '' }}</span>
      <el-select v-else v-model="model.name">
        <el-option v-for="({ name, label }, index) in ways" :key="index" :value="name" :label="label" />
      </el-select>
    </div>

    <!-- 右侧输入或选择 -->
    <div class="right w-40" :class="currentWay.class">
      <el-input v-if="isInput" v-model.trim="model.value" :placeholder="placeholder" clearable :disabled="model.disabled" />
      <el-select v-else v-model.trim="model.value" :placeholder="placeholder" class="" clearable :disabled="model.disabled">
        <el-option v-for="(item, index) in currentWay.values" :key="index" v-bind="item" />
      </el-select>
    </div>
  </div>
</template>

<style scoped lang='scss'>
.left {
  .label {
    border: 1px solid #e5e7eb;
    border-radius: 4px;
    height: 28px;
    color: #666;
    font-size: 12px;
    padding: 0 10px;
    background: #f5f7fa;
    white-space: nowrap;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    transform: translate(1px, 0);
  }
  .el-select :deep(.el-select__wrapper) {
    background: #f5f7fa;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    transform: translateX(1px);
    min-width: 64px;
    width: v-bind(lfw);
  }
}
.right {
  .el-select :deep(.el-select__wrapper) {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
  .el-input :deep(.el-input__wrapper) {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}
</style>
